<template>
	<view>
		<view class="chat">
			<view class="chat-flex chat-column">
				<!-- 1，消息界面 -->
				<view class="chat-msg" @click="closeTool">
					<!-- 
						show-scrollbar="true"
						背景颜色：refresher-background="lightgreen"
						高度：:refresher-threshold="100"
						动画跳转到底部:scroll-with-animation="true"
					 -->
					<scroll-view class="chat-scroll-view" :style="{'height':scrollHeight + 'px'}" scroll-y="true"
						:scroll-into-view="scrollToView" show-scrollbar="true" :scroll-top="scrollTop"
						refresher-enabled="true" :refresher-triggered="triggered" @refresherpulling="onPulling"
						@refresherrefresh="onRefresh" @refresherrestore="onRestore" @refresherabort="onAbort"
						refresher-default-style="white" :refresher-threshold="refresherThreshold"
						refresher-background="#F4F5F6">
						<view class="chat-scroll-view-con">
							<view v-for="(item,index) in chatList" :key="index" :id="'msg' + index">
								<chat-msg-item @imgLoad="imgLoad" :chatItem="item" :chatItemIndex="index"
									@showImg="showImg" @showRedPkg="showRedPkg" @gotoUserSet="gotoUserSet"
									@handleAudio="handleAudio" @longpressItem="longpressItem">

									<template v-slot:chatTime>
										<view>{{computeDate(item.time , index)}}</view>
									</template>
								</chat-msg-item>
							</view>
						</view>
					</scroll-view>
				</view>
				<!-- 2，输入框内容 -->
				<view class="chat-send" :style="{'height':sendHeight + 'px'}">
					<!-- 核心发送框 -->
					<view class="chat-send-core" v-if="!isSendMsg">
						<view class="send-core-input">
							<input placeholder="文明聊天哦..." confirm-type="send" cursor-spacing="40" @confirm="sendMessage"
								ref="inputRef" @input="textareaBInput" v-model="inputcontent"
								:adjust-position="false" />
						</view>
						<view class="send-core-icon">
							<view class="send-icon" @click="clickSendItem(item)" v-for="(item,index) in iconList"
								:key="index">
								<image :src="item.iconImg"></image>
							</view>
						</view>
					</view>

					<view class="chat-send-core" v-else>
						<view class="send-core-input">
							<view class="core-input-view">
								<text>{{sendTitle}}</text>
							</view>
						</view>
						<view class="send-core-icon">
							<view class="send-icon" v-for="(item,index) in iconList" :key="index">
								<image :src="item.iconImg"></image>
							</view>
						</view>
					</view>

					<view class="chat-send-tool">
						<chat-voice v-if="isShowVoiceTool" @sendMsgByUser="sendMsgByUser"></chat-voice>
					</view>
				</view>
			</view>

			<!-- 长按弹框 -->
			<chat-con-tool :popButton="popButton" :showShade="showShade" :showPop="showPop" :popStyle="showHeightStyle"
				@pickerMenu="pickerMenu" @hidePop="closeShowTool"></chat-con-tool>
		</view>

		<chat-add v-if="!isGx" @sendAddUser="sendAddUser"></chat-add>

		<chat-at-animation @selectUser="selectUser" :share="isShowAtGroup" :groupUsers="groupUsers"
			@display="closeAtGroup"></chat-at-animation>


	</view>
</template>

<script>
	//引入公共组件
	import chatMsgItem from './common/chat-msg-item.vue'
	import chatVoice from './common/chat-voice.vue'
	import chatConTool from './common/chat-con-tool.vue'
	import chatAdd from './common/chat-add.vue'
	import chatAtAnimation from './common/chat-at-animation.vue'

	//网络请求
	import {
		uploadFile
	} from '@/api/http/common.js'

	import {
		chooseIamge,
		chooseImageFromCamera
	} from '@/api/uniapp/uni.js'

	import {
		queryGroupUsers
	} from '@/api/http/msg/group.js'

	import {
		handleTime,
		timeago
	} from '@/utils/time/time.js'

	export default {
		props: {
			chatList: {
				type: Array,
				default: []
			},
			msgObjectData: {
				type: Object,
				default: () => {}
			},
			imgList: {
				type: Array,
				default: []
			},
			isGx: {
				type: Boolean,
				default: true
			},
			isSendMsg: {
				type: Boolean,
				default: false
			},
			sendTitle: {
				type: String,
				default: '群聊禁言'
			}
		},
		components: {
			chatMsgItem,
			chatVoice,
			chatConTool,
			chatAdd,
			chatAtAnimation
		},
		data() {
			return {
				userId: uni.getStorageSync('userId'),
				//当前页面可用高度
				screenHeight: 0,
				windowWidth: 0,
				windowHeight: 0,
				//底部输入框高度
				sendHeight: 90,

				scrollToView: '',
				//输入框内容
				inputcontent: '',
				scrollHeight: 300,
				//是否下拉刷新
				triggered: false,
				_freshing: false,
				scrollTop: 0,
				refresherThreshold: 45,

				//底部表情库
				iconList: [{
					id: 1,
					iconImg: require('./static/img/send/01.svg')
				}, {
					id: 2,
					iconImg: require('./static/img/send/02.svg')
				}, {
					id: 3,
					iconImg: require('./static/img/send/03.svg')
				}, {
					id: 4,
					iconImg: require('./static/img/send/04.svg')
				}],

				//语音框展示
				isShowVoiceTool: false,

				//长按弹框
				showShade: false,
				showPop: false,
				showHeightStyle: '',
				popButton: [{
					id: 1,
					text: '撤回',
					img: require('@/static/img/msg/tool/01.svg')
				}, {
					id: 2,
					text: '删除',
					img: require('@/static/img/msg/tool/02.svg')
				}],
				//长按操作的对象
				showPopChatItem: {},
				//艾特信息
				atItem: '',

				//at展示框
				isShowAtGroup: false,
				//群聊成员
				groupUsers: [],
				//键盘是否弹起
				isShowKeyboard: false,


			}
		},
		methods: {
			//1，获取页面高度宽度
			getPageInfo() {
				uni.getSystemInfo({
					success: (res) => {
						this.$nextTick(() => {
							this.screenHeight = res.windowHeight
							this.windowWidth = res.windowWidth
							this.windowHeight = res.windowHeight

							this.changeScrollHeight(90, 0)
						})
					}
				})
			},
			//2，点击底部按钮
			clickSendItem(item) {
				if (item.id == 1) {
					return this.showVoice()
				} else if (item.id == 2) {
					return this.sendImg()
				} else if (item.id == 3) {
					return this.photograph()
				} else {
					return this.sendRedPkg()
				}
			},
			//2.1，图片发送
			sendImg() {
				var that = this
				chooseIamge('album').then(res => {
					const filePaths = res.tempFilePaths
					for (let i = 0; i < filePaths.length; i++) {
						//图片上传
						uploadFile(filePaths[i]).then(result => {
							if (result.data.pubInfo.code !== 0) {
								return uni.$showMsg(result.data.pubInfo.message);
							}
							//var  = result.data.busInfo
							that.sendMsgByUser(result.data.busInfo, 2)
						})

						//this.send(filePaths[i], 1)
					}
				})
			},
			//2.2，照相发送图片
			photograph() {
				var that = this
				chooseImageFromCamera().then(res => {
					uploadFile(res).then(result => {
						if (result.data.pubInfo.code !== 0) {
							return uni.$showMsg(result.data.pubInfo.message);
						}
						//var  = result.data.busInfo
						that.sendMsgByUser(result.data.busInfo, 2)
					})
				})
			},
			//2.3，发送红包
			sendRedPkg() {
				if (!uni.getStorageSync('identifyCheck')) {
					return uni.$showMsg('请先进行实名认证！')
				}
				/* uni.navigateTo({
					url: '/subpkg/msg/red-pkg/red-pkg-select/red-pkg-select?msgObject=' + JSON.stringify(this
						.msgObjectData)
				}) */

				uni.navigateTo({
					url: '/subpkg/msg/red-pkg/red-pkg-send/red-pkg-send?msgObject=' + JSON.stringify(this
						.msgObjectData)
				})
			},
			//2.4，展开或收起语音框
			showVoice() {
				// if (this.isShowKeyboard) {

				// }
				this.isShowVoiceTool = !this.isShowVoiceTool
				if (this.isShowVoiceTool) {
					this.sendHeight = 390
					this.changeScrollHeight(this.sendHeight, 150)
				} else {
					this.sendHeight = 90
					this.changeScrollHeight(this.sendHeight, 150)
				}
			},

			//3，更改，消息高度
			changeScrollHeight(sendHeight, time = 30) {
				this.scrollHeight = this.screenHeight - sendHeight

				this.goBottom(time)
			},
			//4，滚动到底部
			goBottom(time = 30) {
				var that = this
				setTimeout(() => {
					if (that.chatList.length == 0) {
						return
					}
					//console.log('滚动到最底部')
					that.scrollToView = '';
					that.$nextTick(function() {
						let len = that.chatList.length - 1
						that.scrollToView = 'msg' + (len)
					})
				}, time)
			},

			//5，文字消息发送
			sendMessage(e) {
				if (this.atItem == '') {
					this.sendMsgByUser(e.detail.value, 1)
					//console.log(e)
				} else {

					if (e.detail.value.indexOf('@' + JSON.parse(this.atItem).nickname) !== -1) {
						var atMsg = JSON.parse(this.atItem)
						atMsg.atMsgNew = e.detail.value.substring(JSON.parse(this.atItem).nickname.length + 1, e.detail
							.value.length)
						//console.log(atMsg)
						this.sendMsgByUser(JSON.stringify(atMsg), 31)
						this.atItem = ''
					} else {
						this.atItem = ''
						this.sendMsgByUser(e.detail.value, 1)
					}

				}
				setTimeout(() => {
					//清空聊天框
					this.inputcontent = ''
				}, 30)

			},
			sendMsgByUser(msg, types) {
				var data = {
					types,
					msg
				}
				this.$emit('sendMsg', data)
			},

			//6，聊天核心内容操作
			//6.1，点击图片，查看图片
			showImg(e) {
				var that = this
				uni.previewImage({
					current: e.news,
					urls: this.imgList,
					longPressActions: {
						itemList: ['保存图片'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');

							uni.downloadFile({
								url: that.imgList[data.index],
								success: (res) => {
									if (res.statusCode === 200) {
										uni.saveImageToPhotosAlbum({
											filePath: res.tempFilePath,
											success: function() {
												//uniapp提供的消息提示框。
												uni.showToast({
													title: "保存成功",
													icon: "success"
												});
											},
											fail: function() {
												uni.showToast({
													title: "保存失败，请稍后重试",
													icon: "none"
												});
											}
										});
									}
								}
							})

						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				})
			},
			//6.2，跳转用户设置
			gotoUserSet(item) {
				this.$emit("gotoUserSet", item)
			},
			//6.3，图片加载完成
			imgLoad() {},

			//7，键盘监听
			initListener() {
				uni.onKeyboardHeightChange((res) => {
					//键盘高度（根据高度 判断是否弹起）
					let keyBoardHeight = res.height

					if (keyBoardHeight > 0) {
						this.$nextTick(() => {
							this.isShowKeyboard = true
							this.isShowVoiceTool = false
							//键盘弹起
							var newSendHeight = keyBoardHeight + 90
							this.sendHeight = newSendHeight
							//计算可滑动高度
							this.scrollHeight = this.screenHeight - newSendHeight
							this.goBottom(150)
							//this.changeScrollHeight(newSendHeight)
						})
					}
					if (res.height == 0) {
						this.$nextTick(() => {
							if (this.isShowVoiceTool) {

							} else {
								//如果此时，打开其他模态框，则不进行操作
								this.isShowKeyboard = false
								this.sendHeight = 90
								this.scrollHeight = this.screenHeight - 90
								this.goBottom(150)
							}

						})
					}
				})
			},
			//7.1，键盘文字输入
			textareaBInput(e) {
				var inputText = e.detail.value
				//console.log(inputText)
				if (inputText == '@') {
					//console.log('添加@成员')
					queryGroupUsers(this.msgObjectData.id, '', '', '1').then(res => {
						if (res.data.pubInfo.code !== 0) {
							return uni.$showMsg(res.data.pubInfo.message);
						}
						this.groupUsers = res.data.busInfo

						//隐藏键盘
						uni.hideKeyboard()
						this.isShowAtGroup = true
					})

				}
			},
			//7.2，关闭@框
			closeAtGroup() {
				this.isShowAtGroup = false
			},
			//7.3，点击@成员
			selectUser(e) {
				//console.log(e)
				this.atItem = JSON.stringify(e)
				this.isShowAtGroup = false
				this.inputcontent = this.inputcontent.substring(0, this.inputcontent.length - 1)
				this.inputcontent += '@' + e.nickname
			},

			//8，语音播放
			handleAudio(voice) {
				this.$emit("handleAudio", voice)
			},

			//9，上拉加载
			onPulling(e) {},
			onRefresh() {
				if (this._freshing) return;
				this._freshing = true;
				console.log('执行')
				//重新发起请求：请求发送成功以后传入一个回调函数，回调函数停止下拉刷新
				//this.getChatList(this.pageNum)
				this.$emit('getChatListByPage')
			},
			onRestore() {
				this.triggered = 'restore'; // 需要重置
			},
			onAbort() {},
			closeRefreshScroll() {
				this.triggered = false;
				this._freshing = false;
				//console.log('关闭')
				uni.stopPullDownRefresh()
			},

			//10，长按弹出
			longpressItem(item, chatItem) {
				//console.log(chatItem)
				if (chatItem.isWithdraw && chatItem.sendId == this.userId) {
					//可以撤回
					this.popButton = [{
						id: 1,
						text: '撤回',
						img: require('@/static/img/msg/tool/01.svg')
					}, {
						id: 2,
						text: '删除',
						img: require('@/static/img/msg/tool/02.svg')
					}]
				} else {
					//无法撤回
					this.popButton = [{
						id: 2,
						text: '删除',
						img: require('@/static/img/msg/tool/02.svg')
					}]
				}


				this.showPopChatItem = chatItem
				//console.log(item)
				//计算光标高度（距离顶部导航栏的距离）
				var height = parseInt(item.pageY)
				var width = parseInt(item.pageX)
				var bottomHeight = (this.windowHeight - this.sendHeight - 50)
				var leftWidth = this.windowWidth * 0.7
				var rightWidth = this.windowWidth * 0.22
				//this.windowWidth - width

				if (height < 45) {
					//1，如果小于弹框高度则固定位置
					if (width > leftWidth) {
						this.showHeightStyle = `top:60px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `top:60px;left:${width}px;`
					}
				} else if (bottomHeight < height) {
					//2，如果，在底部的话则固定在上面
					if (width > leftWidth) {
						this.showHeightStyle = `bottom:${this.sendHeight + 30}px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `bottom:${this.sendHeight + 30}px;left:${width}px;`
					}
				} else {
					if (width > leftWidth) {
						this.showHeightStyle = `top:${height}px;right:${rightWidth}px;`
					} else {
						this.showHeightStyle = `top:${height}px;left:${width}px;`
					}
				}

				this.showShade = true;
				this.$nextTick(() => {
					setTimeout(() => {
						this.showPop = true;
					}, 10);
				});
			},
			//10.1，关闭弹框
			closeShowTool() {
				this.showPop = false;
				//this.pickerUserIndex = -1;
				setTimeout(() => {
					this.showShade = false;
				}, 10);
			},
			//10.2选择其中的一个
			pickerMenu(item) {
				//console.log(this.showPopChatItem)
				if (item.id == 2) {
					this.$emit('closeUserMsg', this.showPopChatItem)
				} else {
					this.$emit('withdrawUserMsg', this.showPopChatItem)
					//this.sendMsgByUser('撤回一条消息', 11)
				}

			},
			//11，添加好友
			sendAddUser() {
				this.$emit('sendAddUser')
			},
			//12，打开红包
			showRedPkg(item) {
				this.$emit("showRedPkg", item)
			},
			//13，时间处理
			computeDate(createTime, index) {
				if (createTime) {
					if (uni.getSystemInfoSync().platform === 'android') {
						//console.log('运行Android上')
						var datetime = new Date(createTime)
						let date = new Date()

						if (index > 0) {
							//获取上一个
							let beforetime = this.chatList[index - 1].time
							let beforetimestrap = new Date(beforetime)
							if ((datetime - beforetimestrap) > 180000) {
								// date.setTime(datetime)
								// let time = date.toString()
								// let localtime = time.split(" ")[4]
								// return localtime
								return this.getTime(createTime)
							} else {
								return ''
							}
						} else {
							return this.getTime(createTime)
						}

					} else {
						//console.log('运行iOS上')
						var datetime = new Date(createTime.replace(/-/g, '/'))
						let date = new Date()

						if (index > 0) {
							//获取上一个
							let beforetime = this.chatList[index - 1].time
							let beforetimestrap = new Date(beforetime.replace(/-/g, '/'))
							if ((datetime - beforetimestrap) > 180000) {
								// date.setTime(datetime)
								// let time = date.toString()
								// let localtime = time.split(" ")[4]
								// return localtime
								return this.getTime(createTime.replace(/-/g, '/'))
							} else {
								return ''
							}
						} else {
							return this.getTime(createTime.replace(/-/g, '/'))
						}
					}
				} else {
					return ''
				}
			},
			getTime(time) {
				if (uni.getSystemInfoSync().platform === 'android') {
					//console.log('运行Android上')
					return handleTime(time)
				} else {
					//console.log('运行iOS上')
					return handleTime(time.replace(/-/g, '/'))
				}
			},

			//14，关闭语音弹框
			closeTool() {
				this.isShowVoiceTool = false
				this.sendHeight = 90
				this.changeScrollHeight(this.sendHeight, 150)
			}

		},
		mounted() {
			//开启上拉刷新
			this._freshing = false;
			this.triggered = true;

			this.getPageInfo()
			this.initListener()
		},
		onUnload() {
			//关闭键盘监听
			this.destoryListener()
		},


	}
</script>

<style lang="scss" scoped>
	.chat {
		//设置离边框距离
		/* padding: 0 30rpx;

		.chat-flex {
			display: flex;
			flex-direction: row;
		}

		.chat-column {
			flex-direction: column;
		} */
	}

	//消息内容css
	.chat-msg {
		// flex: 1;
		background-color: #F4F5F6;

		.chat-scroll-view {
			//伸缩动画
			transition: height 0.15s;
			-moz-transition: height 0.15s;
			/* Firefox 4 */
			-webkit-transition: height 0.15s;
			/* Safari and Chrome */
			-o-transition: height 0.15s;

			.chat-scroll-view-con {
				padding: 20rpx 0;
			}
		}

	}

	//底部输入框
	.chat-send {
		position: fixed;
		bottom: 0;
		width: 100%;
		background-color: #FFFFFF;

		//伸缩动画
		transition: height 0.15s;
		-moz-transition: height 0.15s;
		/* Firefox 4 */
		-webkit-transition: height 0.15s;
		/* Safari and Chrome */
		-o-transition: height 0.15s;

		.chat-send-core {
			.send-core-input {
				width: 94%;
				// margin: 15px 0px 5px 0px;
				border-radius: 17px;
				// align-content: center;
				font-size: 30rpx;
				margin-left: 3%;
				// height: 45px;
				padding: 8px 0;

				input {
					background-color: #eee;
					border-radius: 17px;
					height: 30px;
					line-height: 30px;
					width: 92%;
					padding: 3px 4%;
					//margin-left: 2%;
				}

				.core-input-view {
					height: 30px;
					width: 92%;
					padding: 3px 4%;
					background-color: #eee;
					border-radius: 17px;
					line-height: 30px;
					text-align: center;
				}
			}

			.send-core-icon {
				height: 34px;
				display: flex;
				width: 100%;

				.send-icon {
					flex: 1;
					text-align: center;

					image {
						width: 28px;
						height: 28px;
					}
				}

			}
		}

		.chat-send-tool {
			width: 100%;
			height: 300px;
		}
	}
</style>